<?php
namespace app\model;
use app\db as DB;

class UserModel {
	
	private $db;
	private $table = 'users';

	public function token($phone)
	{
		$rand = rand(1000,9999);
		return hash('md4', $phone.$rand);
	}

	public function __construct() {
		$this->db = DB::getInstance();
	}

	public function login($phone, $pwd)
	{
		$rs = $this->db->findOne($this->table, 'phone', $phone);
		if(false !== $rs) {
			if( $rs['pwd'] == hash('sha256',$pwd) ) {
				$token = $this->token($phone);
				return [true,0,$token];
			} else {
				return [false,2];//密码错误
			}
		} else {
			return [false,1];//手机号不存在
		}
	}

	public function register($phone, $pwd, $location="")
	{
		$password = hash('sha256',$pwd);
		$reg_time = date('Y-m-d', time());
		$token = $this->token($phone);
		$rs = $this->db->inserts("INSERT INTO users (id,phone,pwd,reg_time,token,reg_location) VALUES (null,'{$phone}','{$password}','{$reg_time}','{$token}','{$location}')");
		if($rs) {
			return [true,0,$token];
		} else {
			return [false,1];
		}
	}

	public function find($phone)
	{
		$rs = $this->db->find($this->table, 'phone', $phone);
		if(false !== $rs) {
			return [true,0,$rs];
		} else {
			return [false,1];
		}
	}

	static public function getUserInfo($phone)
	{

	}
}
